let config = {
    headers: {
      token: localStorage.getItem("token"),
    },
  };
  let userConfig = {
    headers: {
      token: "token",
    },
  };
  
  const handleFileChange = async () => {
    const file = fileInputRef.value.files[0];
    console.log("选择文件已触发")
    if (file) {
      console.log("已找到文件")
      const qiniuKey = await uploadAvatarToQiniu(file);
      if (qiniuKey) {
        console.log("开始上传")
        const domain = 'http://svftekle7.hn-bkt.clouddn.com'; // 替换为你的七牛云存储空间域名
        const avatarUrl = `${qiniuKey}`;
        await sendAvatarUrlToBackend(avatarUrl);
      }
    }
  };

  // 从后端获取上传凭证的函数，这里假设你有一个后端接口可以返回 token
const getUploadToken = async () => {
  try {
    const response = await axios.post('api/user/getQiniuToken',userDto,config)
    console.log(response)
    return response.data.data
    
  } catch (error) {
    console.error('获取上传凭证失败:', error);
    return null;
  }
};

// 上传头像到七牛云的函数
const uploadAvatarToQiniu = async (file) => {
  const token = await getUploadToken();
  QiniuToken.value=token;
  if (!token) {
    console.log("没有token",token)
    return;
  }

  const formData = new FormData();
  formData.append('token', token);
  formData.append('file', file);

  try {
    const response = await axios.post('https://up-z2.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log('上传到七牛云成功:', response.data);
    return response.data.key;
  } catch (error) {
    console.error('上传到七牛云失败:', error);
    return null;
  }
};

// 将图片地址发送给后端的函数
const sendAvatarUrlToBackend = async (url) => {
  try {
    User.value.avator=url
    const response = await axios.post('api/user/changeAvater', User.value);
    console.log('头像地址发送给后端成功:', response.data);
    window.location.reload();
    return response.data;
  } catch (error) {
    console.error('头像地址发送给后端失败:', error);
    return null;
  }
};
 
  export {
    config,userConfig
  }